<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航End -->

    <el-card>
      <el-button
        type="primary"
        class="mb-15"
        @click="addRoleDialogVisible = true"
        >添加角色</el-button
      >

      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="roles">
            <el-row
              v-for="item1 in roles.row.children"
              :key="item1.id"
              class="bt-1"
              type="flex"
              align="middle"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="4">
                <el-tag
                  type="primary"
                  closable
                  @close="delRightsTag(roles.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级和三级权限 -->
              <el-col :span="20">
                <el-row
                  v-for="(item2, idx2) in item1.children"
                  :key="item2.id"
                  :class="[idx2 == 0 ? '' : 'bt-1']"
                  type="flex"
                  align="middle"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="7" :class="['mb-15', 'mt-15']">
                    <el-tag
                      type="success"
                      closable
                      @close="delRightsTag(roles.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="17">
                    <el-row>
                      <!-- 渲染三级权限 -->
                      <el-col
                        :span="5"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                      >
                        <el-tag
                          type="warning"
                          class="m-5"
                          closable
                          @close="delRightsTag(roles.row, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleDialogTable(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="allotRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 角色列表End -->

      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="allotDialogVisible"
        width="30%"
      >
        <el-tree
          :data="rightsList"
          :props="propsTarget"
          :default-checked-keys="defaultExpandItems"
          default-expand-all
          node-key="id"
          show-checkbox
          ref="allotRightsTree"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="allotDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRightsSure">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框End -->

      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
      >
        <el-form ref="addRoleForm" :model="roleData" label-width="80px">
          <el-form-item
            label="角色名称"
            prop="roleName"
            :rules="addRoleRules.roleName"
          >
            <el-input v-model="roleData.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="roleData.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoleSure">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色对话框End -->

      <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%">
        <el-form ref="updateRoleForm" :model="editRoleData" label-width="80px">
          <el-form-item
            label="角色名称"
            prop="roleName"
            :rules="addRoleRules.roleName"
          >
            <el-input v-model="editRoleData.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleData.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色对话框End -->
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      allotDialogVisible: false,
      // 添加角色对话框
      addRoleDialogVisible: false,
      // 修改角色信息
      editDialogVisible: false,
      // 树形控件的属性绑定对象
      propsTarget: {
        children: "children",
        label: "authName",
      },
      // 所有权限数据
      rightsList: [],
      // 默认选中节点的ID值数组
      defaultExpandItems: [],

      // 当前操纵的对象Id
      curRoleId: "",
      curEditRole: {},

      // 添加角色数据
      roleData: {
        roleName: "",
        roleDesc: "",
      },
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "请输入2到10个字符",
            trigger: ["blur", "change"],
          },
        ],
      },

      // 修改角色时的数据
      editRoleData: {
        roleName: "",
        roleDesc: "",
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      let { data: res } = await this.$http("roles");
      this.rolesList = res.data;
      console.log(this.rolesList);
    },

    // 删除用户权限
    delRightsTag(payload, id) {
      this.$confirm("此操作将删除用户的该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { data: res } = await this.$http.delete(
            `roles/${payload.id}/rights/${id}`
          );
          if (res.meta.status != 200)
            return this.$message.error("删除权限失败");
          this.$message.success("删除权限成功");
          // 更新角色权限列表
          payload.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分配权限
    async allotRights(node) {
      this.curRoleId = node.id;

      let { data: res } = await this.$http("/rights/tree");

      if (res.meta.status != 200) this.$message.error("获取权限数据失败");

      this.rightsList = res.data;
      console.log(this.rightsList);
      this.allotDialogVisible = true;

      this.defaultExpandItems = [];
      // 递归获取三级节点的id
      this.setDefaultChecked(node, this.defaultExpandItems);
    },

    // 通过递归，获取角色下所有三级权限的id，
    // 并保存到defaultExpandItems数组中
    // 收集用户默认权限
    setDefaultChecked(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => {
        this.setDefaultChecked(item, arr);
      });
    },

    // 确定角色的权限分配
    async allotRightsSure() {
      let checkeds = this.$refs["allotRightsTree"].getCheckedKeys();
      let halfCheckedes = this.$refs["allotRightsTree"].getHalfCheckedKeys();

      let rightsItems = [...halfCheckedes, ...checkeds];
      rightsItems = rightsItems.join(", ");

      let { data: res } = await this.$http.post(
        `roles/${this.curRoleId}/rights`,
        {
          rids: rightsItems,
        }
      );

      if (res.meta.status != 200) return this.$message.error("分配失败");

      this.$message.success("分配成功");
      this.allotDialogVisible = false;
      // 刷新角色列表
      this.getRolesList();
    },

    // 确定添加角色
    async addRoleSure() {
      let { data: res } = await this.$http.post("/roles", this.roleData);
      if (res.meta.status != 201) return this.$message.error("添加角色失败");
      this.$message.success("添加角色成功");
      this.getRolesList();
      this.addRoleDialogVisible = false;

      this.roleData = {};
    },

    // 打开修改角色对话框
    editRoleDialogTable(payload) {
      this.curEditRole = payload;
      this.editRoleData.roleName = payload.roleName;
      this.editRoleData.roleDesc = payload.roleDesc;
      this.editDialogVisible = true;
    },
    // 保存修改角色信息
    saveRoleEdit() {
      this.$refs.updateRoleForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.put(
          `/roles/${this.curEditRole.id}`,
          this.editRoleData
        );
        if (res.meta.status != 200) return this.$message.error("修改角色失败");
        this.$message.success("修改角色成功");
        this.getRolesList();
        this.editDialogVisible = false;
      });
    },

    // 删除角色
    deleteRole(payload) {
      this.$confirm("此操作将永久删除该橘色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let { data: res } = await this.$http.delete("/roles/" + payload.id);
        if (res.meta.status != 200) return this.$message.error("删除失败");
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.getRolesList();
      });
    },
  },
};
</script>

<style scoped>
.mb-15 {
  margin-bottom: 15px;
}
.mt-15 {
  margin-top: 15px;
}
.m-5 {
  margin: 5px;
}

.bt-1 {
  border-top: 1px solid #efefef;
}
</style>